/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
 */

package pl.droidsonroids.gif;

import ohos.utils.Parcel;
import ohos.utils.Sequenceable;

/**
 * 功能描述
 *
 * @author B71789
 * @since 2020-07-13
 */
public abstract class AbsSavedState implements Sequenceable {
    /**
     * EMPTY_STATE
     */
    public static final AbsSavedState EMPTY_STATE = new AbsSavedState() { };
    /**
     * Create from parcel
     */
    public static final Producer<AbsSavedState> CREATOR
            = new Producer<AbsSavedState>() {
                @Override
                public AbsSavedState createFromParcel(Parcel in) {
                    Sequenceable superState = in.createSequenceable();
                    if (superState != null) {
                        throw new IllegalStateException("superState must be null");
                    }
                    return EMPTY_STATE;
                }
            };

    private Sequenceable mSuperState;

    /**
     * Constructor used to make the EMPTY_STATE singleton
     */
    private AbsSavedState() {
        mSuperState = null;
    }

    /**
     * Constructor called by derived classes when creating their SavedState objects
     *
     * @param superState The state of the superclass of this view
     */
    protected AbsSavedState(Sequenceable superState) {
        if (superState == null) {
            throw new IllegalArgumentException("superState must not be null");
        }
        mSuperState = superState != EMPTY_STATE ? superState : null;
    }

    /**
     * Constructor used when reading from parcel. Reads the state of the superclass.
     *
     * @param source parcel to read from
     */
    protected AbsSavedState(Parcel source) {
        this(source, null);
    }

    /**
     * Constructor used when reading from parcel using given class loader.
     * Reads the state of the superclass.
     *
     * @param source parcel to read from
     * @param loader ClassLoader to use for reading
     */
    protected AbsSavedState(Parcel source, ClassLoader loader) {
        Sequenceable superState = source.createSequenceable();
        mSuperState = superState != null ? superState : EMPTY_STATE;
    }

    public final Sequenceable getSuperState() {
        return mSuperState;
    }

    /**
     * writeToParcel
     *
     * @param dest dest
     * @param flags flags
     */
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeSequenceable(mSuperState);
    }

    @Override
    public boolean marshalling(Parcel parcel) {
        parcel.writeSequenceable(mSuperState);
        return true;
    }

    @Override
    public boolean unmarshalling(Parcel parcel) {
        mSuperState = parcel.createSequenceable();
        return true;
    }
}
